<template>
    <!-- 编辑昵称弹窗 -->
    <el-dialog :append-to-body="true" v-model="visible" width="430" :before-close="handleClose" class="real-name-dialog"
        center>
        <div class="content">
            <h3>实名认证</h3>
            <p>为了您的账户安全，请先完成实名认证</p>

            <el-form ref="formRef" :model="form" label-width="120px" :rules="RealNameRules">
                <el-form-item label="真实姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="请输入身份证号" prop="idCard">
                    <el-input v-model="form.idCard" placeholder="18位身份证号" />
                </el-form-item>
            </el-form>

            <!-- <el-input class="nickname-input" v-model="nickname" placeholder="请输入新昵称" /> -->
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="submitForm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>


<script setup>
import { ref, computed, reactive } from 'vue'
import { domesticUserCenter } from 'ld-web-sdk';
import { ElMessage } from 'element-plus'
import successIcon from '@/assets/images/success-icon.png'
import errorIcon from '@/assets/images/error-icon.png'

import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const formRef = ref(null);
const form = reactive({
    name: '',
    idCard: ''
})

// 身份证号码验证函数
const validateIdCard = (rule, value, callback) => {
    // 基本格式校验
    const idCardReg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!idCardReg.test(value)) {
        callback(new Error('请输入有效的身份证号码'));
        return;
    }

    // 校验码验证
    if (!checkIdCardValidity(value)) {
        callback(new Error('身份证号码校验码不正确'));
        return;
    }

    callback();
};

const RealNameRules = ref({
    name: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
    ],
    idCard: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' },
        { min: 18, max: 18, message: '身份证号码长度必须为18位', trigger: 'blur' },
        { validator: validateIdCard, trigger: 'blur' }
    ],
})

// Props
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    }
})

const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            domesticUserCenter.createUpdateUser().verifyIDcard({
                cardId: form.idCard,
                realName: form.name,
            }).then(res => {
                if (res.code == 200) {

                    ElMessage({
                        type: 'success',
                        customClass: 'custom-success-message-icon',
                        dangerouslyUseHTMLString: true,
                        message: `<img src="${successIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">认证成功`,
                        offset: 65
                    })
                    userStore.RefreshUserInfo()
                    emit('close')
                }
            }).catch(err => {
                console.log('err', err)
                ElMessage({
                    type: 'error',
                    customClass: 'custom-success-message-icon',
                    dangerouslyUseHTMLString: true,
                    message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">${err.message}`,
                    offset: 65
                })
            })

        } else {
            // 验证失败
            console.log('表单验证失败');
            return false;
        }
    });


};

// Refs
const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

// 方法
const handleClose = () => {
    // 重置表单校验错误样式
    if (formRef.value) {
        formRef.value.resetFields();
    }
    emit('close')
}

// Emits
const emit = defineEmits(['update:modelValue', 'close'])


// 身份证号码校验码验证
const checkIdCardValidity = (idCard) => {
    // 加权因子
    const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    // 校验码对应值
    const parityBit = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

    let sum = 0;
    let code = idCard.charAt(17).toUpperCase();

    // 计算前17位与对应因子乘积的和
    for (let i = 0; i < 17; i++) {
        sum += parseInt(idCard.charAt(i)) * factors[i];
    }

    // 计算校验码
    const checkCode = parityBit[sum % 11];

    return code === checkCode;
};
</script>


<style lang="scss">
.real-name-dialog {
    .el-dialog__header {
        padding: 20px !important;

        .el-dialog__title {
            color: #fff;
        }
    }

    .el-dialog__body {
        padding: 0 40px;

        h3 {
            font-size: 20px;
            font-weight: bold;
            color: #fff;
        }

        p {
            margin: 11px 0;
            color: #888;
            font-size: 14px;
        }

        .el-form {
            margin: 30px 0;

            .el-form-item {
                flex-direction: column;
                justify-content: flex-start;

                .el-form-item__label {
                    text-align: left !important;
                    justify-content: flex-start !important;
                    color: #888;
                }
            }
        }
    }

    .el-dialog__footer {
        padding-top: 0 !important;
        padding-bottom: 38px;

        .el-button {
            width: 350px;
            height: 50px;
            background: #ffe500;
            border-color: #ffe500;
            color: #121212;
            font-size: 14px;
            font-weight: bold;
        }
    }
}
</style>
